﻿namespace TestApp.Client
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using Contracts;
    using JetBrains.Annotations;

    internal sealed class AggregationEntityViewModel : EntityViewModel, IAggregationEntityViewModel
    {
        private readonly Dictionary<AggregateType, double?[]> _vals = new Dictionary<AggregateType, double?[]>();
        private AggregateType _selectedAggregate;

        public AggregationEntityViewModel([NotNull] Func<IEntityParamViewModel> paramFactory)
            : base(paramFactory)
        {
        }

        public override string Name
        {
            get { return "Total:"; }
        }

        public AggregateType SelectedAggregate
        {
            get
            {
                return _selectedAggregate;
            }

            set
            {
                _selectedAggregate = value;
                UpdateParams();
                OnPropertyChanged();
            }
        }
       
        public void Update(AggregateEntityDto dataEntity)
        {
            Contract.Requires<ArgumentNullException>(dataEntity != null);
            double?[] curVals;
            if (!_vals.TryGetValue(dataEntity.AggregateType, out curVals))
            {
                _vals[dataEntity.AggregateType] = curVals = new double?[dataEntity.Parameters.Length];
            }

            for (var paramIndex = 0; paramIndex < dataEntity.Parameters.Length; paramIndex++)
            {
                curVals[paramIndex] = dataEntity.Parameters[paramIndex];
            }

            if (dataEntity.AggregateType == SelectedAggregate)
            {
                UpdateParams();
            }
        }

        private void UpdateParams()
        {
            double?[] curVals;
            if (_vals.TryGetValue(SelectedAggregate, out curVals))
            {
                for (var paramIndex = 0; paramIndex < curVals.Length; paramIndex++)
                {
                    Params[paramIndex].UdateValue(curVals[paramIndex]);
                }
            }
            else
            {
                foreach (var valModel in Params)
                {
                    valModel.UdateValue(null);
                }
            }
        }
    }
}
